package com.labor.job.data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang.StringUtils;

/**
 * @File: com.labor.job.data.LaunchTemplatePool.java
 * @Description: 
 *			JOB临时数据池存储、操作
 * @author: Peng.Gao
 * @Email: ronan.gao@vipshop.com
 */
public class JobDataPools<T> implements Serializable {
	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 2804766513522277893L;
	
	private Map<String, T> dataCache = new HashMap<String, T>();
	
	private final ReadWriteLock lock = new ReentrantReadWriteLock();
	
	private final Lock readLock = lock.readLock();
	
	private final Lock writeLock = lock.writeLock();
	
	/**
	 * @Name: flush
	 * @Description: 
	 *			增量式刷新数据
	 * @param caches
	 */
	public void flush(String key, T value){
		writeLock.lock();
	    try {
	    	dataCache.put(key, value);
		} finally {
			writeLock.unlock();
		}
	}
	
	/**
	 * @Name: flush
	 * @Description: 
	 *			批量式刷新数据
	 * @param caches
	 */
	public void flush(Map<String, T> caches){
		writeLock.lock();
	    try {
	    	dataCache.clear();
	    	dataCache.putAll(caches);
		} finally {
			writeLock.unlock();
		}
	}
	
	/**
	 * @Name: get
	 * @Description: 
	 *			根据“key”获取缓存数据
	 * @param key
	 * @return
	 */
	public T get(String key) {
		readLock.lock();
		try{
			if (StringUtils.isBlank(key)) {
				return null;
			} else {
				return dataCache.get(key);
			}
		} finally {
			readLock.unlock();
		}
	}
	
	/**
	 * @Name: get
	 * @Description: 
	 *			获取所有Key-Value缓存数据
	 * @return
	 */
	public Map<String, T> get() {
		readLock.lock();
		try{
			return dataCache;
		} finally {
			readLock.unlock();
		}
	}
}
